<template>
  <div class="min-h-screen">
    <!-- 面包屑 - 移动端调整 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 pt-16 sm:pt-20">
      <a-breadcrumb class="py-3 sm:py-4 text-sm sm:text-base">
        <a-breadcrumb-item>
          <a href="/" data-readdy="true">首页</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item class="truncate max-w-[120px] sm:max-w-none">{{
          params.title
        }}</a-breadcrumb-item>
      </a-breadcrumb>
      <a-page-header
        style="
          border: 1px solid rgb(235, 237, 240);
          background: white;
          border-radius: 8px;
        "
        title="返回"
        class="!p-3 sm:!p-4"
        @back="() => router.back()"
      />
    </div>
    <!-- 主要内容区 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 py-1">
      <div class="flex flex-col lg:flex-row gap-4 sm:gap-8">
        <!-- 左侧文章内容 -->
        <div v-if="password.status != 20111" class="flex-1 order-2 lg:order-1">
          <a-spin size="large" v-if="!article.content" />
          <article class="bg-white rounded-lg shadow-sm p-4 sm:p-6 lg:p-8">
            <!-- 标题 -->
            <h1 class="text-2xl sm:text-3xl font-bold mb-3 sm:mb-4">
              {{ article.title }}
            </h1>
            <!-- 文章信息 - 移动端调整为垂直布局 -->
            <div
              class="flex flex-wrap items-center gap-3 sm:gap-6 mb-6 sm:mb-8 text-sm sm:text-base text-gray-600"
            >
              <div class="flex items-center w-full sm:w-auto">
                <img
                  :src="article.users.avatar"
                  alt="作者头像"
                  class="w-8 h-8 sm:w-10 sm:h-10 rounded-full"
                />
                <span class="ml-2">{{ article.users.username }}</span>
              </div>
              <div class="flex items-center">
                <clock-circle-outlined class="text-sm sm:text-base" />
                <span class="ml-1">{{ article.createdAt }}</span>
              </div>
              <div class="flex items-center">
                <eye-outlined class="text-sm sm:text-base" />
                <span class="ml-1">{{ article.views }}</span>
              </div>
              <div class="flex items-center">
                <like-outlined class="text-sm sm:text-base" />
                <span class="ml-1">{{ article.likes }}</span>
              </div>
            </div>
            <!-- 文章封面 -->
            <div class="mb-6 sm:mb-8 rounded-lg overflow-hidden">
              <img
                :src="article.coverImage"
                alt="文章封面"
                style="height: 350px"
                class="w-full"
              />
            </div>
            <!-- 文章内容 -->
            <div class="max-w-none text-sm sm:text-base">
              <div v-if="false" v-html="article.content"></div>
              <div v-else ref="divRef" class="max-w-none text-sm sm:text-base">
                <div class="aie-container" style="border: none">
                  <div class="aie-container-header" style="display: none"></div>
                  <div
                    class="aie-container-footer none"
                    style="display: none"
                  ></div>
                </div>
              </div>
            </div>
            <!-- 点赞区域 -->
            <div class="flex justify-center mt-8 sm:mt-12">
              <a-button
                type="primary"
                size="large"
                class="!rounded-button whitespace-nowrap flex items-center !h-10 sm:!h-auto"
                :class="{ 'bg-red-500': isLiked }"
                @click="handleLike"
              >
                <like-outlined class="text-sm sm:text-base" />
                <span class="ml-1 sm:ml-2 text-sm sm:text-base">{{
                  isLiked ? "已点赞" : "点赞"
                }}</span>
              </a-button>
            </div>
            <!-- 评论区 -->
            <div class="mt-8 sm:mt-12">
              <h3 class="text-lg sm:text-xl font-bold mb-4 sm:mb-6">评论区</h3>
              <!--禁止评论-->
              <div
                v-if="
                  article.allowComment === 'N' || config.sysIsComment === 'N'
                "
                class="mt-6 sm:mt-8"
              >
                <div class="bg-gray-50 p-4 sm:p-6 rounded-lg">
                  <div class="text-gray-700 text-sm sm:text-base">
                    此文章已禁止评论
                  </div>
                </div>
              </div>
              <div v-else class="bg-gray-50 p-4 sm:p-6 rounded-lg mb-6 sm:mb-8">
                <!-- 评论表单 - 移动端改为垂直布局 -->
                <div class="flex flex-col sm:flex-row gap-4 mb-3 sm:mb-4">
                  <div class="w-full sm:w-1/2 space-y-2 sm:space-y-0 comment">
                    <a-input
                      v-model:value="commentFrom.nickname"
                      placeholder="您的昵称"
                      size="small"
                      class="sm:mb-2 nickname"
                    />
                    <a-input
                      v-model:value="commentFrom.email"
                      placeholder="您的邮箱（选填）"
                      size="small"
                    />
                  </div>
                  <div class="w-full sm:w-1/2 space-y-2 sm:space-y-0">
                    <a-input
                      v-model:value="commentFrom.website"
                      placeholder="您的网站（选填）"
                      size="small"
                      class="sm:mb-2"
                    />
                    <a-input
                      v-model:value="commentFrom.avatar"
                      placeholder="头像URL（选填）"
                      size="small"
                    />
                  </div>
                </div>
                <div style="border: 1px solid #ccc">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                  />
                  <Editor
                    style="height: 300px; overflow-y: hidden"
                    v-model="commentFrom.content"
                    @onCreated="handleCreated"
                  />
                </div>
                <div class="flex justify-between items-center">
                  <div
                    class="text-xs sm:text-sm text-gray-500"
                    v-if="replyingTo"
                  >
                    回复给：{{ replyingTo.nickname }}
                    <a-button type="link" size="small" @click="cancelReply"
                      >取消回复</a-button
                    >
                  </div>
                  <a-button
                    type="primary"
                    class="!rounded-button whitespace-nowrap !h-8 sm:!h-auto mt-3"
                    @click="submitComment"
                  >
                    <span class="text-sm sm:text-base">发表评论</span>
                  </a-button>
                </div>
              </div>
              <!-- 评论列表 -->
              <div class="mt-6 sm:mt-8">
                <!--评论数量-->
                <div class="flex items-center justify-between">
                  <div class="text-gray-700 text-sm sm:text-base">
                    {{ commentCount }} 条评论
                  </div>
                </div>
                <CommentTree
                  :comments="comments"
                  @reply="handleReply"
                  v-if="comments.length > 0"
                />
                <a-empty description="暂无评论" v-else />
              </div>
            </div>
          </article>
        </div>
        <div v-else class="flex-1 order-2 lg:order-1">
          <!--输入密码-->
          <div class="mb-6 sm:mb-8">
            <div class="bg-gray-50 p-4 sm:p-6 rounded-lg">
              <span>文章已加密</span>
              <div class="mt-4">
                <a-input
                  v-model:value="password.password"
                  placeholder="请输入密码"
                  class="mb-3 sm:mb-4"
                />
                <a-button
                  type="primary"
                  class="!rounded-button whitespace-nowrap !h-8 sm:!h-auto"
                  @click="checkPassword"
                >
                  <span class="text-sm sm:text-base">查看</span>
                </a-button>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧边栏 - 移动端放在顶部 -->
        <div class="w-full lg:w-80 order-1 lg:order-2">
          <!-- 作者信息 -->
          <MyInfo />
          <!-- 相关文章 -->
          <RelatedArticle class="mt-3" />
        </div>
      </div>
    </main>
  </div>
</template>

<script lang="ts" setup>
import {
  computed,
  nextTick,
  onBeforeUnmount,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  shallowRef,
} from "vue";
import {
  ClockCircleOutlined,
  EyeOutlined,
  LikeOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import type { ArticleVo, CommentDto, CommentVo } from "@/type";
import { useRoute, useRouter } from "vue-router";
import { commentApi, postApi, sysApi } from "@/api";
import { CommentTree, RelatedArticle } from "./index.ts";
import MyInfo from "@/views/Home/MyInfo.vue";
import dayjs from "dayjs";
import { debounce } from "lodash-es";
import { AiEditor } from "aieditor";
import "aieditor/dist/style.css";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import type { IToolbarConfig } from "@wangeditor/editor";
import { useCounterStore } from "@/stores/counter.ts";

const route = useRoute();
const router = useRouter();

const editorRef = shallowRef();
const counterStore = useCounterStore();

const config = computed(() => counterStore.config);
// console.log(config.value)
const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    // 菜单 key
    "italic", // 斜体
    "through", // 删除线
    "underline", // 下划线
    "color", // 文字颜色
    "lineHeight", // 行高
    "delIndent", // 缩进
    "indent", // 增进
    "divider", // 分割线
    "justifyCenter", // 居中对齐
    "justifyJustify", // 两端对齐
    "justifyLeft", // 左对齐
    "justifyRight", // 右对齐
    "clearStyle", // 清除格式
    "codeBlock", //代码块
    "insertLink",
  ],
};
const divRef = ref();
let aiEditor: AiEditor | null = null;

const isLiked = ref(false);
const params = route.params;
const commentCount = ref(0);

const replyingTo = ref<CommentDto | null>(null);
const article = ref<ArticleVo>({
  categoryName: "",
  content: "",
  coverImage: "",
  createdAt: "",
  id: 0,
  allowComment: "",
  likes: 0,
  tags: [],
  title: "",
  users: {
    id: 0,
    username: "",
    avatar: "",
  },
  views: 0,
});
const commentFrom = reactive<CommentDto>({
  content: "",
  postId: article.value.id as number,
  avatar: "",
  parentId: null,
  nickname: "",
  email: "",
  website: "",
});

const setContent = (content: string) => {
  aiEditor = new AiEditor({
    element: divRef.value as Element,
    toolbarKeys: [],
    editable: false,
    contentRetention: true,
    draggable: false,
    content: content,
  });
};
const password = ref({ status: 0, password: "" });
const comments = ref<CommentVo[]>([]);

const checkPassword = async () => {
  if (!password.value.password) {
    message.error("请输入查看密码");
  } else {
    const res = await postApi.getPost(
      params.id as any,
      password.value.password,
    );
    if (res.code !== 20111) {
      password.value.status = 0;
      password.value.password = "";
      article.value = {
        ...res.data,
        createdAt: dayjs(res.data.createdAt).format("YYYY-MM-DD"),
      };
      setTimeout(() => {
        setContent(res.data.content);
      });
      await getCommentList(params.id as any);
    } else {
      message.error(res.message);
    }
  }
};

// 点赞
const handleLike = debounce(
  async () => {
    if (isLiked.value) return;
    isLiked.value = true;
    const res = await postApi.setLike(article.value.id as number);
    // 接口返回后解除防抖锁定
    setTimeout(() => {
      isLiked.value = false;
    }, 1000);
    res.status ? message.success(res.message) : message.error(res.message);
  },
  500,
  { leading: true, trailing: false },
);
// 首次点击立即执行，忽略后续连续点击
const handleReply = (comment: CommentVo) => {
  replyingTo.value = {
    nickname: comment.nickname,
    avatar: comment.avatar,
    parentId: comment.id,
  } as CommentDto;
  // console.log("replyingTo", replyingTo.value)
  // 滚动到评论框
  const ele = document.querySelector(".comment") as HTMLElement;
  const nicknameEle = document.querySelector(".nickname") as HTMLElement;
  nicknameEle.focus();
  window.scrollTo({
    top: ele?.offsetTop - 100,
    behavior: "smooth",
  });
};

const cancelReply = () => {
  replyingTo.value = null;
};

const submitComment = async () => {
  if (!commentFrom.nickname.trim()) {
    message.warning("昵称不能为空");
    return;
  }
  if (commentFrom.content.trim()) {
    const newComment: CommentDto = {
      website: commentFrom.website.trim() || "",
      nickname: commentFrom.nickname.trim() || "匿名用户",
      avatar:
        commentFrom.avatar ||
        "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
      content: commentFrom.content.trim(),
      postId: article.value.id,
      email: commentFrom.email?.trim() || "",
      parentId: replyingTo.value?.parentId || null,
      level: replyingTo.value?.parentId ? 2 : 1,
    };
    const res = await commentApi.addComment(newComment);
    if (res) {
      message.success("评论成功");
      replyingTo.value = null;
      await getCommentList(article.value.id);
    } else {
      message.error("评论失败");
    }
    // 清空表单
    init();
  } else {
    message.warning("评论内容不能为空");
  }
};
// 初始化
const init = () => {
  replyingTo.value = null;
  commentFrom.parentId = null;
  commentFrom.content = "";
  commentFrom.nickname = "";
  commentFrom.email = "";
  commentFrom.avatar = "";
};
const getArticleById = async (id: number) => {
  const data = await postApi.getPost(id, null);
  if (data.code !== 20111) {
    article.value = {
      ...data.data,
      createdAt: dayjs(data.data.createdAt).format("YYYY-MM-DD"),
    };
    setContent(data.data.content);
    await getCommentList(id);
  } else {
    password.value.status = data.code;
  }
};
const getCommentList = async (id: number) => {
  const res = await commentApi.getCommentList(id);
  commentCount.value = res.total;
  comments.value = res.comments;
};
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

onMounted(() => {
  getArticleById(params.id as any);
  counterStore.getSysConfig();
  // setTimeout(() => {
  //   console.log(editorRef.value.getAllMenuKeys(''))
  // },2000)
});
onUnmounted(() => {
  aiEditor && aiEditor.destroy();
});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style scoped>
.prose {
  color: #374151;
  max-width: 65ch;
  font-size: 1rem;
  line-height: 1.6;
}

@media (min-width: 640px) {
  .prose {
    font-size: 1.125rem;
    line-height: 1.75;
  }
}

/* 移动端优化Ant Design组件 */
@media (max-width: 640px) {
  :deep(.ant-page-header-heading-title) {
    font-size: 14px;
  }

  :deep(.ant-breadcrumb) {
    font-size: 12px;
  }

  :deep(.ant-btn-lg) {
    height: 36px;
    padding: 0 12px;
  }

  :deep(.ant-input),
  :deep(.ant-input-affix-wrapper),
  :deep(.ant-input-textarea) {
    font-size: 14px;
  }
}
</style>
